import './App.css';
import LoginPage from './components/loginscreen/LoginPage';
import HomePage from './components/mainscreen/MainPage';
import { Routes, Route, Navigate, useNavigate, useLocation } from 'react-router-dom';
import Header from './components/base/Header';
import FeedingPage from './components/infoPages/Feeding';
import { useEffect, useState } from 'react';
import PopulationsPage from './components/infoPages/Populations';
import SensorDataPage from './components/infoPages/SensorsDataPage';
import EquipmentPage from './components/infoPages/EquipmentPage';
import axios from "axios";
import SettingPage from './components/base/Settings';

const isAuthenticated = async () => {
  const body = {};
  let auth = false;
  if (localStorage.getItem('refresh')) {
    body["refreshToken"] = localStorage.getItem('refresh');
    try {
      axios.post(`${process.env.REACT_APP_API_BASE_URL}/refresh-token`, body).then((response) => {
        localStorage.setItem('access', response.data.accessToken);
      
      })
      auth = true;
    } catch (error) {
      if (error.response.status === 401 || error.response.status === 403) {
        localStorage.setItem('access', null);
        localStorage.setItem('refresh', null);
      }
    }
  } else {
    auth = false;
  }
  return auth;
};

function App() {
  const [auth, setAuth] = useState(false);
  const [redirect, setRedirect] = useState(true);
  const navigate = useNavigate();
  const location = useLocation();
  const from = location.state?.from?.pathname;

  useEffect(() => {
    const checkAuth = async () => {
      const authenticated = await isAuthenticated();
      setAuth(authenticated);
      if (!authenticated) {
        navigate('/login')
      }
      else{
        console.log(from)
        navigate(from, { replace: true });
      }
    };
    checkAuth();
  }, []);

  
  useEffect(() => {
    console.log(auth)
    if(auth){
      setRedirect(auth)
    }
  }, [auth])


  return (
    <div className="App">
      {redirect && <Header />}
      <Routes>
        <Route path="/home" element={redirect ? (
          <HomePage />
        ) : (
          <Navigate to="/login" />
        )} />
        <Route path="/settings" element={redirect ? (
          <SettingPage />
        ) : (
          <Navigate to="/login" />
        )} />
        <Route path="/login" element={<LoginPage />} />
        <Route path="/feed" element={redirect ? (
          <FeedingPage />
        ) : (
          <Navigate to="/login" />
        )}></Route>
        <Route path="/population" element={redirect ? (
          <PopulationsPage />
        ) : (
          <Navigate to="/login" />
        )}></Route>
        <Route path="/water" element={redirect ? (
          <SensorDataPage />
        ) : (
          <Navigate to="/login" />
        )}></Route>
        <Route path='/equipment' element={redirect ? (
          <EquipmentPage />
        ) : (
          <Navigate to="/login" />
        )}></Route>
      </Routes>
    </div>
  );
}

export default App;
